<template>
  <div class="bg-gray-50 min-h-screen py-8">
    <div class="max-w-5xl mx-auto px-4 sm:px-6 lg:px-8">
      <el-card class="comment-card shadow-lg">
        <template #header>
          <div class="flex justify-between items-center px-2 py-3 border-b border-gray-200">
            <h1 class="text-2xl font-bold text-gray-800">批量评论</h1>
          </div>
        </template>

        <!-- URL管理部分 -->
        <el-tabs
            type="border-card"
            class="custom-tabs mt-6"
        >
          <el-tab-pane label="手动添加" name="manual">
            <div class="url-input-container">
              <el-input
                  v-model="newUrl"
                  placeholder="请输入URL"
                  class="flex-1"
                  size="large"
              >
                <template #append>
                  <el-button
                      @click="handleAddUrl"
                      type="primary"
                      class="hover:opacity-90 transition-opacity"
                  >
                    <span class="px-2">添加</span>
                  </el-button>
                </template>
              </el-input>
            </div>
          </el-tab-pane>

          <el-tab-pane label="文件上传" name="upload">
            <div class="upload-container p-6 bg-gray-50 rounded-lg border-2 border-dashed border-gray-300">
              <el-upload
                  ref="uploadRef"
                  class="upload-area flex flex-col items-center"
                  action="#"
                  :auto-upload="false"
                  :on-change="handleFileChange"
                  accept=".xlsx,.xls"
                  drag
              >
                <el-icon class="text-4xl text-gray-400 mb-2"><Upload /></el-icon>
                <div class="text-gray-600">将文件拖到此处或</div>
                <el-button type="primary" size="large" class="mt-4">选择文件</el-button>
                <template #tip>
                  <div class="el-upload__tip">
                    请上传Excel文件，要求：
                    <ul>
                      <li>支持 .xlsx 和 .xls 格式</li>
                      <li>每行一个网址</li>
                      <li>对同一个网站多次评论，失败率高。</li>
                    </ul>
                    <el-button
                        link
                        type="primary"
                        @click="downloadTemplate"
                    >
                      下载Excel模板
                    </el-button>
                  </div>
                </template>
              </el-upload>
            </div>
          </el-tab-pane>
        </el-tabs>

        <!-- URL预览列表 -->
        <div v-if="commentsStore.urlList.length > 0" class="url-list-container mt-8">
          <div class="list-header flex justify-between items-center mb-4">
            <h2 class="text-lg font-semibold text-gray-800">URL列表</h2>
            <el-button
                type="danger"
                plain
                @click="handleClearUrls"
                class="hover:bg-red-50 transition-colors"
            >
              清空列表
            </el-button>
          </div>

          <el-table
              :data="paginatedUrls"
              style="width: 100%"
              class="custom-table mb-4"
              :header-cell-style="{
              background: '#f8fafc',
              color: '#475569'
            }"
          >
            <el-table-column prop="url" label="URL">
              <template #default="{ row }">
                <div class="flex items-center justify-between py-2">
                  <span class="truncate flex-1 text-gray-700">{{ row.url }}</span>
                  <el-button
                      type="danger"
                      link
                      @click="handleRemoveUrl(row)"
                      class="hover:text-red-600"
                  >删除</el-button>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" width="120">
              <template #default="{ row }">
                <el-tag
                    :type="row.status === '成功' ? 'success' : row.status === '失败' ? 'danger' : 'info'"
                    size="small"
                >
                  {{ row.status || '等待中' }}
                </el-tag>
              </template>
            </el-table-column>
          </el-table>

          <el-pagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :total="commentsStore.urlList.length"
              :page-sizes="[10, 20, 30, 50]"
              layout="total, sizes, prev, pager, next"
              @size-change="handleSizeChange"
              @current-change="handlePageChange"
              class="flex justify-end mt-4"
              background
          />
        </div>

        <!-- 评论表单 -->
        <el-form
            :model="commentsStore.formData"
            label-position="top"
            class="comment-form mt-8"
        >
          <el-form-item
              label="评论内容"
              required
              class="mb-6"
          >
            <el-input
                v-model="commentsStore.formData.commentContent"
                type="textarea"
                :rows="4"
                placeholder="请输入评论内容"
                resize="none"
                class="transition-all focus:shadow-md"
            />
          </el-form-item>

          <el-row :gutter="24">
            <el-col :span="12">
              <el-form-item label="昵称" required>
                <div class="input-group flex">
                  <el-input
                      v-model="commentsStore.formData.nickname"
                      placeholder="请输入昵称"
                      class="flex-1"
                  />
                  <el-button
                      @click="generateRandomNickname"
                      class="ml-3 hover:bg-gray-50 transition-colors"
                  >
                    随机生成
                  </el-button>
                </div>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="邮箱" required>
                <div class="input-group flex">
                  <el-input
                      v-model="commentsStore.formData.email"
                      placeholder="请输入邮箱"
                      class="flex-1"
                  />
                  <el-button
                      @click="generateRandomEmail"
                      class="ml-3 hover:bg-gray-50 transition-colors"
                  >
                    随机生成
                  </el-button>
                </div>
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="网站链接">
            <el-input
                v-model="commentsStore.formData.websiteUrl"
                placeholder="请输入网站链接（选填）"
                class="transition-all focus:shadow-md"
            />
          </el-form-item>
        </el-form>

        <!-- 操作按钮 -->
        <div class="action-buttons flex justify-center space-x-4 mt-8">
          <el-button
              type="primary"
              :loading="commentsStore.isLoading"
              @click="handleSubmit"
              size="large"
              class="w-32 hover:opacity-90 transition-opacity"
          >
            {{ commentsStore.isLoading ? '发送中...' : '发送评论' }}
          </el-button>
          <el-button
              @click="handleReset"
              size="large"
              class="w-32 hover:bg-gray-50 transition-colors"
          >
            重置
          </el-button>
        </div>

        <!-- 消息提示 -->
        <el-alert
            v-if="commentsStore.message"
            :type="commentsStore.message.includes('失败') ? 'error' : 'success'"
            :title="commentsStore.message"
            show-icon
            class="mt-6"
        />
      </el-card>
    </div>
  </div>
</template>
<script setup>
import { ref, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import {ElMessage, ElMessageBox} from 'element-plus'
import * as XLSX from 'xlsx'
import { useCommentsStore } from '@/stores/adminComment'
import {Upload} from "@element-plus/icons-vue";

const uploadRef = ref(null)
const currentPage = ref(1)
const pageSize = ref(10)
const commentsStore = useCommentsStore()
const router = useRouter()
const newUrl = ref('')
const totalUrls = ref(0)

// 手动添加URL
const handleAddUrl = () => {
  if (!newUrl.value || !newUrl.value.trim().startsWith('http')) {
    ElMessage.warning('请输入有效的URL地址')
    return
  }

  const url = newUrl.value.trim()
  if (commentsStore.urlList.some(item => item.url === url)) {
    ElMessage.warning('该URL已存在')
    return
  }

  // 创建新的URL对象，与文件上传时的格式保持一致
  const newUrlObject = {
    url: url,
    status: '待处理'
  }

  // 使用 addUrl 添加到列表中
  commentsStore.addUrl(newUrlObject)
  newUrl.value = ''
  ElMessage.success('URL添加成功')
}

// 删除单个URL
const handleRemoveUrl = (row) => {
  const index = commentsStore.urlList.findIndex(item => item.url === row.url)
  if (index > -1) {
    commentsStore.urlList.splice(index, 1)
    ElMessage.success('删除成功')
  }
}

// 清空URL列表
const handleClearUrls = () => {
  ElMessageBox.confirm('确定要清空URL列表吗？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    commentsStore.clearUrlList()
    ElMessage.success('列表已清空')
  })
}

// 生成随机昵称
const generateRandomNickname = () => {
  const adjectives = [
    'Happy', 'Clever', 'Lovely', 'Kind', 'Elegant',
    'Brave', 'Playful', 'Charming', 'Cheerful', 'Curious',
    'Energetic', 'Gentle', 'Lively', 'Merry', 'Quick',
    'Shiny', 'Witty', 'Bright', 'Adventurous', 'Calm'
  ];

  const nouns = [
    'Kitten', 'Puppy', 'Rabbit', 'Bird', 'Bear',
    'Fox', 'Panda', 'Squirrel', 'Deer', 'Otter',
    'Penguin', 'Hedgehog', 'Owl', 'Dolphin', 'Koala',
    'Butterfly', 'Bee', 'Caterpillar', 'Lamb', 'TigerCub'
  ];

  const randomAdjective = adjectives[Math.floor(Math.random() * adjectives.length)];
  const randomNoun = nouns[Math.floor(Math.random() * nouns.length)];
  commentsStore.formData.nickname = `${randomAdjective}${randomNoun}`;
};


// 生成随机邮箱
const generateRandomEmail = () => {
  const domains = ['gmail.com', 'yahoo.com', 'hotmail.com', 'outlook.com', 'qq.com', '163.com'];

  // 生成随机字符串，包含字母和数字
  const randomString = Math.random().toString(36).substring(2, 10) +
      Math.random().toString(36).toUpperCase().substring(2, 6);

  // 加入时间戳的部分（隐藏大部分，只取毫秒后两位）
  const timestampFragment = Date.now().toString().slice(-2);

  // 随机选择域名
  const randomDomain = domains[Math.floor(Math.random() * domains.length)];

  // 拼接邮箱地址
  commentsStore.formData.email = `${randomString}${timestampFragment}@${randomDomain}`;
};

const downloadTemplate = () => {
  // 创建工作簿
  const wb = XLSX.utils.book_new()

  // 示例数据
  const exampleData = [
    ['https://jirkatoman.cz/?p=78222772'],
    ['https://jammiesuebeauty.com/whats-next-for-us'],
    ['https://sysnapssolution.com/index.php/2022/07/27/coldzera-esportowyym-ambasadorem-parimatch'],
    ['https://westofeden.com/calendar/west-of-eden-are-playing-taube-at-ostansjo-on-3010-2021'],
    ['https://www.petra-fabinger.de/2018/03/04/werde-im-maerz-gastgeberin-es-lohnt-sich'],
    ['https://jirkatoman.cz/?p=78233919'],
    ['https://jirkatoman.cz/?p=78351932'],
    ['https://jirkatoman.cz/?p=78426691']
  ]

  // 创建工作表
  const ws = XLSX.utils.aoa_to_sheet(exampleData)

  ws['!cols'] =  [{ wch: 100 }]

  // 将工作表添加到工作簿
  XLSX.utils.book_append_sheet(wb, ws, '示例')

  // 生成Excel文件并下载
  XLSX.writeFile(wb, '批量评论URL模板.xlsx')
}

//文件上传
const handleFileChange = (file) => {
  if (!file.raw) {
    ElMessage.error('文件上传失败')
    return
  }

  const reader = new FileReader()
  reader.onload = (e) => {
    try {
      const data = new Uint8Array(e.target.result)
      const workbook = XLSX.read(data, { type: 'array' })
      const firstSheetName = workbook.SheetNames[0]
      const worksheet = workbook.Sheets[firstSheetName]

      // 提取所有URL
      const allUrls = XLSX.utils.sheet_to_json(worksheet, { header: 1 })
          .flat()
          .filter(url => url && typeof url === 'string' && url.trim().startsWith('http'))

      totalUrls.value = allUrls.length

      // URL去重（注意：现在要和已有的URL一起去重）
      const existingUrls = new Set(commentsStore.urlList.map(item => item.url))
      const newUniqueUrls = allUrls.filter(url => !existingUrls.has(url.trim()))

      // 格式化新的URL并添加到列表中
      const formattedUrls = newUniqueUrls.map(url => ({
        url: url.trim(),
        status: '待处理'
      }))

      // 逐个添加新URL，而不是替换整个列表
      formattedUrls.forEach(urlData => {
        commentsStore.addUrl(urlData)
      })

      if (formattedUrls.length > 0) {
        ElMessage.success(`文件解析成功，共发现 ${totalUrls.value} 个URL，去重后剩余 ${formattedUrls.length} 个URL`)
        // 成功后清除文件列表
        uploadRef.value?.clearFiles()
      } else {
        ElMessage.warning('未在文件中发现有效的URL')
      }
    } catch (error) {
      console.error('Excel解析错误:', error)
      ElMessage.error('Excel文件解析失败')
    }
  }

  reader.readAsArrayBuffer(file.raw)
}

// 分页数据
const paginatedUrls = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return commentsStore.urlList.slice(start, end)
})

// 处理分页变化
const handlePageChange = (val) => {
  currentPage.value = val
}

const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
}

// 重置表单
const handleReset = () => {
  commentsStore.clearForm()
  // 清除上传文件列表
  if (uploadRef.value) {
    uploadRef.value.clearFiles()
  }
  ElMessage.info('表单已重置')
}

// 发送批量评论请求
const handleSubmit = async () => {
  try {
    // 不需要在这里转换数据，直接调用 store 的方法
    let result = await commentsStore.sendBatchComments();

    if (result.success) {
      ElMessage.success(`评论任务创建成功，批次号: ${result.batchNo}`)
      // 可以在这里添加批次号的处理逻辑
      await router.push(`/admin-comment/listDetail/${result.batchNo}`)
    } else {
      throw new Error(result.error || '评论提交失败')
    }
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error(error.message || '评论提交失败')
  }
}

</script>
<style scoped>
/* 自定义输入框样式 */
.el-input :deep(.el-input__wrapper),
.el-input :deep(.el-textarea__inner) {
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
  border: 1px solid #e5e7eb;
  border-radius: 0.5rem;
  transition: all 0.2s ease;
}

/* 输入框悬停效果 */
.el-input :deep(.el-input__wrapper:hover),
.el-input :deep(.el-textarea__inner:hover) {
  border-color: #60a5fa;
  box-shadow: 0 2px 8px rgba(96, 165, 250, 0.15);
}

/* 输入框聚焦效果 */
.el-input :deep(.el-input__wrapper.is-focus),
.el-input :deep(.el-textarea__inner:focus) {
  border-color: #3b82f6;
  box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.1);
}

/* 文本域特殊样式 */
.el-input :deep(.el-textarea__inner) {
  padding: 0.75rem;
  line-height: 1.5;
  min-height: 120px;
}

/* 输入框内部填充 */
.el-input :deep(.el-input__inner) {
  height: 42px;
  padding: 0 1rem;
}

/* 输入框placeholder样式 */
.el-input :deep(.el-input__inner::placeholder),
.el-input :deep(.el-textarea__inner::placeholder) {
  color: #9ca3af;
  opacity: 0.8;
}

/* 禁用状态样式 */
.el-input.is-disabled :deep(.el-input__wrapper),
.el-input.is-disabled :deep(.el-textarea__inner) {
  background-color: #f9fafb;
  border-color: #e5e7eb;
  cursor: not-allowed;
  opacity: 0.75;
}

/* 错误状态样式 */
.el-input.is-error :deep(.el-input__wrapper),
.el-input.is-error :deep(.el-textarea__inner) {
  border-color: #ef4444;
  box-shadow: 0 0 0 1px rgba(239, 68, 68, 0.1);
}

/* 输入组样式优化 */
.input-group {
  display: flex;
  gap: 0.75rem;
  align-items: center;
}

/* URL输入框特殊样式 */
.url-input-container .el-input :deep(.el-input__wrapper) {
  border-top-right-radius: 0;
  border-bottom-right-radius: 0;
}

/* 表单项标签样式 */
.el-form-item :deep(.el-form-item__label) {
  font-weight: 600;
  color: #374151;
  margin-bottom: 0.5rem;
  font-size: 0.95rem;
}
.comment-card {
  background: white;
  border-radius: 0.5rem;
}

.custom-tabs :deep(.el-tabs__content) {
  padding: 20px;
}

.custom-table :deep(.el-table__row) {
  transition: background-color 0.2s;
}

.custom-table :deep(.el-table__row:hover) {
  background-color: #f8fafc;
}

.upload-container {
  transition: all 0.3s ease;
}

.upload-container:hover {
  border-color: #60a5fa;
}
</style>